package com.example.wzdjcrdpassword.interceptor;

import com.example.wzdjcrdpassword.entity.SystemEntity;
import com.example.wzdjcrdpassword.service.SystemService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Optional;

@Component
@Slf4j
@RequiredArgsConstructor
public class AppIdInterceptor implements HandlerInterceptor {
    
    private final SystemService systemService;
    
    // 需要验证appId的接口路径
    private static final String[] PROTECTED_PATHS = {
        "/api/validation/card-password",
        "/api/validation/config",
        "/api/system/create",
        "/api/system/update",
        "/api/system/delete",
        "/api/user-report/submit"
    };
    
    // 不需要验证appId的接口路径
    private static final String[] EXCLUDED_PATHS = {
        "/api/system/all",
        "/api/system/",
        "/api/system/type/",
        "/api/system/search"
    };
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        
        log.info("拦截器处理请求: {} {}", method, requestURI);
        
        // 检查是否为需要验证的路径
        if (!isProtectedPath(requestURI)) {
            return true;
        }
        
        // 获取appId请求头
        String appId = request.getHeader("appId");
        
        if (appId == null || appId.trim().isEmpty()) {
            log.warn("请求缺少appId请求头: {} {}", method, requestURI);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"success\":false,\"message\":\"缺少appId请求头\"}");
            return false;
        }
        
        // 验证appId是否存在
        Optional<SystemEntity> systemOpt = systemService.getSystemById(appId);
        
        if (systemOpt.isEmpty()) {
            log.warn("无效的appId: {} - 请求: {} {}", appId, method, requestURI);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"success\":false,\"message\":\"无效的appId\"}");
            return false;
        }
        
        SystemEntity system = systemOpt.get();
        log.info("appId验证通过: {} - 系统名称: {}", appId, system.getSystemName());
        
        // 将系统信息设置到请求属性中，供后续使用
        request.setAttribute("systemInfo", system);
        
        return true;
    }
    
    /**
     * 检查请求路径是否需要验证appId
     */
    private boolean isProtectedPath(String requestURI) {
        // 先检查是否在排除列表中
        for (String excludedPath : EXCLUDED_PATHS) {
            if (requestURI.startsWith(excludedPath)) {
                return false;
            }
        }
        
        // 检查是否在保护列表中
        for (String protectedPath : PROTECTED_PATHS) {
            if (requestURI.equals(protectedPath) || requestURI.startsWith(protectedPath + "/")) {
                return true;
            }
        }
        
        return false;
    }
}